package com.yzt.dynamicmodule;

import android.net.Uri;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.message.RXGameMessageContent;
import com.yzt.zhuju.network.entity.game.GameConversationBean;
import com.yzt.zhuju.rongyun.IMMessageType;

import java.util.List;

import io.rong.imkit.IMCenter;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.IRongCoreCallback;
import io.rong.imlib.IRongCoreEnum;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.chatroom.base.RongChatRoomClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;

/**
 * 作者：bobwang
 * 创建时间：2024-01-08 23:13:49
 * 描述： 游戏管理器
 * https://doc.rongcloud.cn/im/Android/5.X/noui/chatroom/join
 */
public class GameManager {

    //private final MutableLiveData<ChatRoomAction> chatRoomActionLiveData = new MutableLiveData<>();

    private static final String TAG = "GameManager";

    public static GameManager instance;

    private String rongRoomId;


    public GameManager() {

    }

    public static GameManager getInstance() {
        if (null == instance) {
            instance = new GameManager();
        }
        return instance;
    }

    public void setRongRoomId(String rongRoomId) {
        this.rongRoomId = rongRoomId;
    }

    public void joinRoom() {

        int defMessageCount = 50;

        RongChatRoomClient.getInstance().joinExistChatRoom(rongRoomId, defMessageCount, new IRongCoreCallback.OperationCallback() {

            @Override
            public void onSuccess() {
                // 处理成功加入聊天室的情况
                Log.e(TAG, "成功加入聊天室------------->");
            }

            @Override
            public void onError(IRongCoreEnum.CoreErrorCode e) {
                // 可以根据错误代码进行适当的处理和向用户提供反馈
                Log.e(TAG, "加入聊天室失败。错误代码: " + e.getValue());
            }
        });
    }

    /**
     * 离开房间
     */
    public void leaveRoom() {
        RongChatRoomClient.getInstance().quitChatRoom(rongRoomId, new IRongCoreCallback.OperationCallback() {

            public void onSuccess() {

            }

            @Override
            public void onError(IRongCoreEnum.CoreErrorCode coreErrorCode) {

            }
        });
    }

    /**
     * 初始化聊天室监听
     */
    public void initChatRoomActionListener() {

        RongChatRoomClient.setChatRoomAdvancedActionListener(new RongChatRoomClient.ChatRoomAdvancedActionListener() {
            @Override
            public void onJoining(String roomId) {
                Log.e(TAG, "onJoining------------->");
                // chatRoomActionLiveData.postValue(ChatRoomAction.joining(roomId));
            }

            @Override
            public void onJoined(String roomId) {
                Log.e(TAG, "onJoined------------->");
                // chatRoomActionLiveData.postValue(ChatRoomAction.joined(roomId));
            }

            @Override
            public void onReset(String roomId) {
                Log.e(TAG, "onReset------------->");
                //  chatRoomActionLiveData.postValue(ChatRoomAction.reset(roomId));
            }

            @Override
            public void onQuited(String roomId) {
                Log.e(TAG, "onQuited------------->");
                //  chatRoomActionLiveData.postValue(ChatRoomAction.quited(roomId));
            }

            @Override
            public void onDestroyed(String chatRoomId, IRongCoreEnum.ChatRoomDestroyType type) {
                Log.e(TAG, "onDestroyed------------->");
                //chatRoomActionLiveData.postValue(ChatRoomAction.destroyed(chatRoomId));
            }

            @Override
            public void onError(String chatRoomId, IRongCoreEnum.CoreErrorCode code) {
                Log.e(TAG, "onError------------->" + code.getMessage());
                // chatRoomActionLiveData.postValue(ChatRoomAction.error(chatRoomId));
            }
        });
    }

    public void initMsgCallback() {
        IMCenter.getInstance().addOnReceiveMessageListener(new RongIMClient.OnReceiveMessageWrapperListener() {
            @Override
            public boolean onReceived(Message message, int i, boolean b, boolean b1) {
                // TODO: 2024/1/7 消息回调
                if (message.getObjectName().equals(IMMessageType.GAME_IN_MESSAGE)) {
                    //聊天室消息
                    RXGameMessageContent bean = (RXGameMessageContent) message.getContent();

                    // 进入房间
                    if (bean.getMsgType().equals("OCM:roomJoin")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                       // ToastUtil.showMessage("roomJoin");
                    }
                    // 离开房间
                    if (bean.getMsgType().equals("OCM:roomLeave")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                       // ToastUtil.showMessage("roomLeave");
                    }
                    // 踢出房间
                    if (bean.getMsgType().equals("OCM:roomKick")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                        //ToastUtil.showMessage("roomKick");
                    }
                    // 惩罚牌
                    if (bean.getMsgType().equals("OCM:GamePunishCard")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackConversation(conversationBean);
                       // ToastUtil.showMessage("GamePunishCard");
                    }
                    // 红包
                    if (bean.getMsgType().equals("OCM:GameRedPacket")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackConversation(conversationBean);
                      //  ToastUtil.showMessage("GameRedPacket");
                    }
                    // 红包领取通知
                    if (bean.getMsgType().equals("OCM:GameRedPacketOpen")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackConversation(conversationBean);
                      //  ToastUtil.showMessage("GameRedPacketOpen");
                    }
                    // 礼物
                    if (bean.getMsgType().equals("OCM:GameGift")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackConversation(conversationBean);
                      //  ToastUtil.showMessage("GameGift");
                    }
                    // 切换主持人
                    if (bean.getMsgType().equals("OCM:GameChangeRole")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                        ToastUtil.showMessage("GameChangeRole");
                    }
                    // 开始游戏
                    if (bean.getMsgType().equals("OCM:GameStart")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                        ToastUtil.showMessage("GameStart");
                    }
                    // 下一关
                    if (bean.getMsgType().equals("OCM:NextMission")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackConversation(conversationBean);
                        ToastUtil.showMessage("NextMission");
                    }
                    // 结束游戏
                    if (bean.getMsgType().equals("OCM:GameOver")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                        ToastUtil.showMessage("GameOver");
                    }
                    // 退出游戏
                    if (bean.getMsgType().equals("OCM:GameQuit")) {
                        GameConversationBean conversationBean = JSONObject.parseObject(bean.getJsonContent(), GameConversationBean.class);
                        messageCallBackOnCLickListener.onMessageCallBackNotify(conversationBean);
                        ToastUtil.showMessage("GameQuit");
                    }

                    Log.e("gameRoomMessage", JSONObject.toJSONString(message));
                }
                return false;
            }
        });
    }

    public void getHistory() {

        Conversation.ConversationType conversationType = Conversation.ConversationType.CHATROOM;
        int oldestMessageId = -1;
        final int count = 10;

        final long recordTime = 0;

        RongIMClient.getInstance().getHistoryMessages(conversationType, rongRoomId, oldestMessageId, count,
                new RongIMClient.ResultCallback<List<Message>>() {

                    @Override
                    public void onSuccess(List<Message> messages) {
                        if (messages == null || messages.isEmpty()) {
                            RongChatRoomClient.getInstance().getChatroomHistoryMessages(rongRoomId, recordTime, count, IRongCoreEnum.TimestampOrder.RC_TIMESTAMP_ASC,
                                    new IRongCoreCallback.IChatRoomHistoryMessageCallback() {

                                        @Override
                                        public void onSuccess(List<Message> messages, long syncTime) {
                                            Log.e("tag", "成功了-------" + JSON.toJSONString(messages));
                                        }


                                        @Override
                                        public void onError(IRongCoreEnum.CoreErrorCode code) {
                                            Log.e("tag", "失败了-------" + code);
                                        }
                                    });

                        }
                    }

                    @Override
                    public void onError(RongIMClient.ErrorCode errorCode) {
                        Log.e("tag", "失败大了-------" + errorCode);
                    }
                });
    }

    /**
     * 发送图片消息
     *
     * @param path 图片路径
     */
    public void sendImg(String path) {
        Conversation.ConversationType conversationType = Conversation.ConversationType.CHATROOM;
        //图片本地路径，接收方可以通过 getThumUri 获取自动生成的缩略图 Uri
        if (!path.startsWith("content://") && !path.startsWith("file://")) {
            path = "file://" + path;
        }
        Uri localUri = Uri.parse(path);
        ImageMessage mediaMessageContent = ImageMessage.obtain(localUri, true);
        Message message = Message.obtain(rongRoomId, conversationType, mediaMessageContent);
        String finalPath = path;
        IMCenter.getInstance().sendMediaMessage(message, null, null, new IRongCallback.ISendMediaMessageCallback() {

            @Override
            public void onProgress(Message message, int i) {

            }

            @Override
            public void onCanceled(Message message) {

            }

            @Override
            public void onAttached(Message message) {

            }

            @Override
            public void onSuccess(Message message) {
                Log.e(TAG, "onSuccess------------->");
                GameConversationBean conversationBean = new GameConversationBean();
                conversationBean.setMsgType("OCM:GamePic");
                conversationBean.setPicUrl(finalPath);
                conversationBean.setSendUserId(RXingUtils.getPersonDetail().getUserBasic().getUserId());
                messageCallBackOnCLickListener.onMessageCallBackConversation(conversationBean);
            }

            @Override
            public void onError(final Message message, final RongIMClient.ErrorCode errorCode) {
                Log.e(TAG, "send_msg_onError------------->" + errorCode.msg);
            }
        });
    }

    private MessageCallBackOnCLickListener messageCallBackOnCLickListener;

    public void setMessageCallBackOnCLickListener(MessageCallBackOnCLickListener listener) {
        if (messageCallBackOnCLickListener == null) {
            messageCallBackOnCLickListener = listener;
        }
    }


    public interface MessageCallBackOnCLickListener {

        void onMessageCallBackConversation(GameConversationBean bean);

        void onMessageCallBackNotify(GameConversationBean bean);
    }

}
